package engine.newUi
{
	import engine.data.BindManage;
	import engine.data.ModelLocator;
	import engine.data.ObjectData;
	import engine.data.View;
	import engine.data.ViewObject;
	import engine.flag.ResourcesPath;
	import engine.logic.tips.TipsManage;
	import engine.net.messages.CustomToServerFlag;
	import engine.net.mgr.SystemSender;
	import engine.tip.tipItem.BookKungfuItem;
	import engine.ui.MsgTipsLogic;
	
	import flash.display.MovieClip;
	import flash.events.MouseEvent;
	
	import newx.com.config.StaticIni;
	import newx.com.control.NxClip;
	import newx.com.control.comboBox.NxComboBoxEvent;
	import newx.com.control.window.NxWindowEvent;
	import newx.utils.FilterUtil;

	/**
	 * 
	 * @author zhouqiang
	 * 
	 */	
	public class EmulatePartnerLogic
	{
		
		private const CURRENT_INDEX:String="currentIndex"
		private static var _self:EmulatePartnerLogic;
		
		private var _bind:BindManage;
		
		private var _model:ModelLocator;
		
		private var _ui:EmulatePartnerUI;
		
		private var _giftArr:Array;
		
		/**绑定练功类型标签*/
		private var _bindTypeIndex:int	= -1;
		
//		/**绑定练功类型标签*/
		private var _blindFlag:int= -1;
		
		/**绑定刷新按钮次数*/
		private var _bindCountIndex:int	= -1;
		
		private var _bindPartnerIndex:int	=	-1;
		
		/**绑定伙伴等级标签数组*/
		private var _bindIndexObj:Object;
		
		/**储存所有伙伴*/
		private var _boxList:Array;
		
		/**伙伴的ID*/
		private var _partnerID:int;
		
		/**第几个师傅*/
		private var _index:int;
		
		/**伙伴的等级*/
		private var _partenerLevel:int
		
		/**伙伴的经验*/
		//private var _partenerExp:int
		
		/**绑定伙伴等级index*/
		private var _bindpartnerExp:Object;
		
		/**基础加成经验*/
		private var _baseExp:Array;
		
		/**基础师傅等级加成*/
		private var _LevelArr:Array;
		
		/**师傅状态加成*/
		private var _typeArr:Array;
		
		private var _getType:int;
		
		/**师傅等级*/
		private var _emulateLevel:int
		
		/**在出战状态的伙伴*/
		private var _inListArr:Array;
		
		/**在出战状态的伙伴*/
		//private var _inListArr:Array;
		
		private var effectMC:MovieClip;
		
		private var _isShowEffec:Boolean	=false;
		
		private var _isShowTips:Boolean	=false;
		/**上一次礼物的等级*/
		private var _lastGIftLeve:int;
		//private var _showCount:int;
		public static function getInstance():EmulatePartnerLogic
		{
			if(_self == null)
			{
				_self	=	new EmulatePartnerLogic();
			}
			return _self
		}
		
		public function get ui():EmulatePartnerUI
		{
			if(_ui==null)
			{
				_ui	=	new EmulatePartnerUI();
			}
			return _ui
		}
		public function EmulatePartnerLogic()
		{
		}
		
		public function Init():void
		{
			_giftArr	=	[];
			_baseExp	=	[];
			_LevelArr	=	[];
			_typeArr	=	[];	
			_inListArr	=	[];
			_model		=	ModelLocator.getInstance();
			_bind		=	BindManage.getInstance();
			_bindIndexObj	=	new Object();
			//绑定伙伴
//			var strUr:String	=	"res/swf/"+"effect11"+".swf";
//			SwfLoader.StartLoad(strUr,null,addSwfHandle);
			var str:String		=	StaticIni.getIniVar("EmulateExpConfig","arr");
			var levelStr:String	=	StaticIni.getIniVar("EmulateExpConfig","level");
			var typeStr:String	=	StaticIni.getIniVar("EmulateExpConfig","type");
			_baseExp	=	str.split(",");
			_LevelArr	=	levelStr.split(",");
			_typeArr	=	typeStr.split(",");
			ui.upEffect.visible	=	false;
			if(_blindFlag==-1)
			{
				//				trace("EmbattleControl.addAllListener()阵法绑定");
				_blindFlag = _bind.BindRecord(_model.scene,"LineupRecord",onaddPerHandle,onremovePerHandle);
			}
		}
		
		/**
		 * 打拜师选择界面 
		 * @param index
		 * 
		 */		
		public function showUI(index:int,level:int):void
		{
			_index			=	index;
			_emulateLevel	=	level;
			ui.showOrHide();
		}
		
		public function BeforeShow():void
		{
			InitGiftImg();
			addInit();
			_boxList	=	[];
			//_inListArr	=	[];
			ui.comBox.showCount	=	1;
			if(_bindPartnerIndex == -1)
			{
				_bindPartnerIndex	=	_bind.BindView(_model.scene,View.VIEWPORT_PARTNER,OnAddPartner,OnRemovePartner);
			}
			//绑定练功状态
			if(_bindTypeIndex == -1)
			{
				_bindTypeIndex	=	_bind.BindProp(_model.scene.Role,"PractiseType",this,"onExpTypeHandle");
			}
			
			if(_bindCountIndex == -1)
			{
				_bindCountIndex	=	_bind.BindProp(_model.scene.Role,"TodayRefreshPractiseTimes",this,"MultiLvChange");	
			}
			ui.levelShow.visible	=	false;
			_boxList.sort(sortOfLevel);
			ui.comBox.dataProvider	=	_boxList;	
			if(currentSelet)
			{
				var index:int=_boxList.indexOf(currentSelet);
			}
			else
			{
				index=0;
//				currentSelet=_boxList[0]
				if(_boxList.length == 0)return
				ui.comBox.data.HandleProperties(CURRENT_INDEX,_boxList[0].data);
			}
			ui.comBox.showCount		=	_boxList.length;
//			if(ui.comBox.getSelecedItem() == null)return;
			ui.comBox.setSelected(index);
			currentSelet	=	ui.comBox.dataProvider[index]
			var view:ViewObject	=	(ui.comBox.getSelecedItem() as Object).data;
			_partnerID			=	view.GetProperties("ConfigID");
			isShowUpBtn(view);
			ui.headClip.source	=	ResourcesPath.getMiniHeadPic(view.GetProperties("Model"));
			unbindPartnerLevel();
			_bindIndexObj[_partnerID]	=	_bind.BindProp(view,"Level",this,"getLevel");
		}
		
		/**
		 * 判断当前伙伴的等级是否小于主角的等级 
		 * @param view
		 * 
		 */		
		private function isShowUpBtn(view:ObjectData):void
		{
			var myLevel:int	=	_model.scene.roleLevel;
			var partnerLev:int	=	view.GetProperties("Level");
			if(partnerLev < myLevel)
			{
				ui.levelShow.visible	=	false;
				ui.beginBtn.visible		=	true;
			}
			else
			{
				ui.levelShow.visible	=	true;
				ui.beginBtn.visible		=	false;
			}
		}
		/**
		 * 解除伙伴等级绑定 
		 * 
		 */		
		private function unbindPartnerLevel():void
		{
//			for(var j:int = 0; j < _boxList.length;j++)
//			{
//				_bind.UnbindView(_boxList[j]["data"],
//			}for each (var i:int in _bindIndexObj) 
			for (var prop:String in _bindIndexObj)
			{
				if(_bindIndexObj[prop] == 1)
				{
					_bindIndexObj[prop]=_bind.UnbindProp(getView(prop),"Level",_bindIndexObj[prop]);
				}
			}
		}
		
		/**
		 * 根据configID得到对应的ViewObject 
		 * @param str
		 * @return 
		 * 
		 */		
		private function getView(str:String):ViewObject
		{
			for(var j:int = 0; j < _boxList.length;j++)
			{	
				if(_boxList[j]["data"].GetProperties("ConfigID") == str)
				{
					return _boxList[j]["data"]
				}
			}
			return null
		}
		/**
		 * 出战的伙伴 
		 * @param PropertiesName
		 * @param PropertiesValue
		 * @param data
		 * 
		 */		
		public function onaddPerHandle(PropertiesName:String,PropertiesValue:Array,data:*):void
		{
			//伙伴在伙伴容器中的位置
			var PartnerIndex:String		= 	PropertiesValue[2];
			_inListArr[int(PropertiesName)]	=	PropertiesValue[2];
		}
		
		public function onremovePerHandle(PropertiesName:String,PropertiesValue:Array,data:*):void
		{
			_inListArr[int(PropertiesName)]	=	0;
		}
		private var currentSelet:Object;
		/**
		 * 伙伴个数增加 
		 * @param PropertiesName
		 * @param PropertiesValue
		 * @param data
		 * 
		 */		
		private function OnAddPartner(PropertiesName:String,PropertiesValue:ViewObject,data:*):void
		{
			var isIn:String	=	isInList(int(PropertiesName));
			var str:String	=	PropertiesValue.GetProperties("Name")+" Lv: "
										+ PropertiesValue.GetProperties("Level")
										+ isIn;
			var isFight:Boolean = isInFight(int(PropertiesName));
			PropertiesValue.HandleProperties("isFight",isFight)
			var obj:Object={label:str,data:PropertiesValue};
			_boxList.push(obj);
			if(PropertiesValue==ui.comBox.data.GetProperties(CURRENT_INDEX))
			{
//				trace("EmulatePartnerLogic.OnAddPartner(PropertiesName, PropertiesValue, data)",_boxList.indexOf(obj));
//				 ui.comBox.data.HandleProperties(CURRENT_INDEX,	_boxList.indexOf(obj));
				currentSelet=obj;
			}
		}
		
		/**
		 * 按宝宝的等级排序 
		 * @param _boxList
		 * 
		 */		
		private function sortOfLevel(a:Object,b:Object):int
		{
			//trace(a["data"].GetProperties("Level") +"==----=-=-=")
			var numa:int	=	a["data"].GetProperties("Level");
			var numb:int	=	b["data"].GetProperties("Level");
			//if(a["data"].GetProperties("Level") > a["data"].GetProperties("Level"))
			var isfighta:Boolean =  a["data"].GetProperties("isFight");
			var isfightb:Boolean =  b["data"].GetProperties("isFight");
			if(!isfighta&&isfightb)
			{
				return 1
			}
			else if(isfighta&&!isfightb)
			{
				return -1
			}
			else 
			{
				return numb - numa;
			}
		}
		
		private function isInFight(val:int):Boolean
		{
			var str:Boolean;
			for(var j:int = 0; j < _inListArr.length;j++)
			{
				if(val == _inListArr[j])
				{
					str = true;	
					break;
				}
				else
				{
					str = false;
				}
			}
			return str	
		}
		
		private function isInList(val:int):String
		{
			var str:String;
			for(var j:int = 0; j < _inListArr.length;j++)
			{
				if(val == _inListArr[j])
				{
					str = StaticIni.getSwfLangStr("UIString_1000282")
					return str	
				}
				else
				{
					str	=	StaticIni.getSwfLangStr("UIString_1000283");
				}
			}
			return str	
		}
		/**
		 * 伙伴个数减少 
		 * @param PropertiesName
		 * @param PropertiesValue
		 * @param data
		 * 
		 */		
		private function OnRemovePartner(PropertiesName:String,PropertiesValue:ViewObject,data:*):void
		{
			var obj:Object 	= 	{label:PropertiesValue.GetProperties("Name"),
				data:PropertiesValue}
			for(var i:int = 0; i < _boxList.length;i++)
			{
				if((_boxList[i] as Object)["data"] == PropertiesValue.GetProperties("ConfigID"))
				{
					_boxList.splice(i,1);
				}
			}
			ui.comBox.dataProvider		=	_boxList;
			if(_boxList.length < 1)
			{
				ui.comBox.clear();
			}
			//当前显示伙伴ID
			_boxList			=	(ui.comBox.getSelecedItem() as Object).data;
			ui.headClip.source	=	ResourcesPath.getMiniHeadPic(_partnerID);
			ui.comBox.showCount	=	_boxList.length;
		}
		
		/**
		 * 绑定练功回调函数
		 * val 练功类型0,1,2,3,4
		 */
		public function set onExpTypeHandle(val:String):void
		{
			for(var i:int = 0;i < 5;i++)
			{
				ui["gift"+i] .filters	=	[FilterUtil.GrayColorFilter];
			}
			ui["gift"+val] .filters	=	[];
			ui.nowlab.htmlText	 =	StaticIni.getSwfLangStr("BaiShiUIStr_06") +
				StaticIni.getSwfLangStr("BaiShiUIStr_0"+val);
			_getType	=	int(val);
			ui.explab.htmlText	=	StaticIni.getSwfLangStrVar("UIString_1000234",[canGet(_getType)])
			if(_isShowEffec && int(val) > _lastGIftLeve)
			{
				ui.upEffect.visible	=	true;
				ui.upEffect.gotoAndPlay(1);
				ui.upEffect.x	=	ui["gift"+val] .x-17;
				ui.upEffect.y	=	ui["gift"+val] .y-16;
				ui.upEffect.addFrameScript(ui.upEffect.totalFrames - 1,mcOverHandle);
				//_lastGIftLeve	=	int(val);
			}
//			if(_isShowEffec)	
//			{
			ui.effect.visible	=	true;
			ui.effect.x			=	ui["gift"+val] .x-17;
			ui.effect.y			=	ui["gift"+val] .y-16;
				//ui.effect.addFrameScript(ui.effect.totalFrames - 1,mcOverHandle);	
			_lastGIftLeve	=	int(val);
		//	}

			//当状态达到最高时 刷新按钮不可点击	
			if(int(val) == 4)
			{
				_ui.refreshBtn.enabled		=	false;
				_ui.refreshBtn.filters		=	[FilterUtil.GrayColorFilter];
			}
			else
			{
				_ui.refreshBtn.enabled		=	true;
				_ui.refreshBtn.filters		=	[];
			}
			//onRefreshOverHandle();
		}
		
		/**
		 * 绑定刷新次数 
		 * @param val
		 * 
		 */		
		public function set MultiLvChange(val:int):void
		{
			onRefreshOverHandle();
		}
		
		/**
		 * 特效播完后执行函数 
		 * 
		 */		
		private function mcOverHandle():void
		{
			ui.upEffect.stop();
			ui.upEffect.visible	=	false;
		}
		/**
		 * 初始化礼物图片 
		 * 
		 */		
		private function InitGiftImg():void
		{
			for(var i:int = 0;i < 5;i++)
			{
				(_ui["gift"+String(i)] as NxClip).source	=	"res/png/gift_"+String(i)+".png";
				(_ui["gift"+String(i)] as NxClip).filters	=	[FilterUtil.GrayColorFilter];
				(_ui["gift"+String(i)] as NxClip).addEventListener(MouseEvent.ROLL_OUT,onGiftOutTipsHandle);
				(_ui["gift"+String(i)] as NxClip).addEventListener(MouseEvent.ROLL_OVER,onGiftOverTipsHandle);
				(_ui["gift"+String(i)] as NxClip).data.HandleProperties("index",i);
				_giftArr.push(_ui["gift"+String(i)] as NxClip);			
			}
			ui.levelLab.mouseEnabled	=	false;
			//ui.effect.visible			=	false;
			ui.headBack.gotoAndStop(1);	
			ui.effect.gotoAndPlay(1);
		}
		
		/**
		 * 增加侦听事件 
		 * 
		 */		
		private function addInit():void
		{
			ui.refreshBtn.addEventListener(MouseEvent.CLICK,onRefreshHandle);	
			ui.refreshBtn.addEventListener(MouseEvent.ROLL_OUT,onGiftOutTipsHandle);	
			ui.refreshBtn.addEventListener(MouseEvent.ROLL_OVER,onRefreshOverHandle);	
			ui.beginBtn.addEventListener(MouseEvent.CLICK,onbeginClickHandle);
			ui.comBox.addEventListener(NxComboBoxEvent.NXCOMBOBOX_CLICK,onBoxClickHandle);
			ui.windowBG.addEventListener(NxWindowEvent.WINDOW_CLOSE,onClickCloseHandle);
		}
		
		
		/**
		 * box下拉菜单点击事件 
		 * @param e
		 * 
		 */		
		private function onBoxClickHandle(e:NxComboBoxEvent):void
		{
			var data:ObjectData	=	e.item.data as ObjectData;
			var headId:int			=	int(data.GetProperties("Model"));
			//bindpatenrExp(view,_partnerID);
			ui.headClip.source	=	ResourcesPath.getMiniHeadPic(headId);
			_partnerID			=	data.GetProperties("ConfigID")
			// 要解决重复绑定
//			if(_bindpartnerExp[_partnerID] == -1)
//			{_partnerID
			unbindPartnerLevel();
			_bindIndexObj[_partnerID]	=	_bind.BindProp(data,"Level",this,"getLevel");
			ui.comBox.data.HandleProperties(CURRENT_INDEX,e.item.data)
			//}
			isShowUpBtn(data);
		}
		/**
		 * 师父状态刷新 
		 * @param e
		 * 
		 */		
		private function onRefreshHandle(e:MouseEvent):void
		{
			_isShowEffec	=	true;
			SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_REFRESH_PRACTISE_TYPE)
		}
		
		/**
		 * 开始练功 
		 * @param e
		 * 
		 */		
		private function onbeginClickHandle(e:MouseEvent):void
		{
			if(_boxList.length <= 0)
			{
				NoticeUI.getInstance().showInfo(StaticIni.getSwfLangStr("UIString_1000303"));
				return
			}	
			ui.hide();
			SystemSender.getInstance().CustomMsgEx(
					CustomToServerFlag.CLIENT_CUSTOMMSG_REQUEST_PRACTISE,[5,(_index+1),_partnerID]);
		//	var _tipLogic:MsgTipsLogic = MsgTipsLogic.getRes(ui.beginBtn);
		//	var str:String = StaticIni.getSwfLangStrVar("97194",[canGet(_getType)]);
			//_tipLogic.showInfo(str);
		}
		/**
		 * 关闭tips
		 * @param e
		 * 
		 */	
		private function onGiftOutTipsHandle(e:MouseEvent):void
		{
			_isShowTips = false;
			TipsManage.hideTips();
		}
		
		/**
		 * 送师父礼物tips
		 * @param e
		 * 
		 */	
		private function onGiftOverTipsHandle(e:MouseEvent):void
		{
			var mc:NxClip	=	e.target as NxClip;
			var index:int	=	mc.data.GetProperties("index");
			//var get:int		=	_baseExp[_partenerLevel]*(1+_emulateLevel)*(1+index);
			TipsManage.showTips(
				StaticIni.getSwfLangStrVar("BaiShiTipsStr_0"+String(index),[canGet(index)]));			
		}
			
		/**
		 * 刷新tips
		 * @param e
		 * 
		 */	
		private function onRefreshOverHandle(e:MouseEvent=null):void
		{
			if(e !=null)
			{
				_isShowTips	=true
			}
			if(_isShowTips == false)return
			var num:int		=	_model.scene.Role.GetProperties("TodayRefreshPractiseTimes");
			var money:int;
			if(num < 10)
			{
				money	=	(num+1)*2
			}
			else
			{
				money	=	20;
			}
			TipsManage.showTips(
				StaticIni.getSwfLangStrVar("UIString_1000253",[money]));			
		}
		
		/**
		 * 返回可得到的经验 
		 * @param index
		 * @return 
		 * 
		 */		
		private function canGet(index:int):int
		{
			var level:int	=	_model.scene.roleLevel;
			var get:Number		=	Number(_baseExp[level-1])*(1+Number(_LevelArr[_emulateLevel-1]))*(1+Number(_typeArr[index]));
			return Math.floor(get);
			
		}
		/**
		 * 绑定伙伴等级 
		 * @param val
		 * 
		 */		
		public function set getLevel(val:int):void
		{
			_partenerLevel	=	val;
			ui.levelLab.htmlText	=	StaticIni.getSwfLangStrVar("UIString_1000233",[val]);
			var view:ViewObject	=	(ui.comBox.getSelecedItem() as Object).data;
			_partnerID			=	view.GetProperties("ConfigID");
			isShowUpBtn(view);
		}
	
		public function AfterHide():void
		{
			_bindTypeIndex		=	_bind.UnbindProp(_model.scene.Role,"PractiseType",_bindTypeIndex);
			//_blindFlag			=	_bind.UnbindRecord("LineupRecord",_blindFlag);
			_bindPartnerIndex	=	_bind.UnbindView(View.VIEWPORT_PARTNER,_bindPartnerIndex);
			removeEvent();
		}
		
		
		/**
		 * 注销侦听事件 
		 * 
		 */		
		private function removeEvent():void
		{
			ui.refreshBtn.removeEventListener(MouseEvent.CLICK,onRefreshHandle);	
			ui.refreshBtn.removeEventListener(MouseEvent.ROLL_OUT,onGiftOutTipsHandle);	
			ui.refreshBtn.removeEventListener(MouseEvent.ROLL_OVER,onRefreshOverHandle);	
			ui.beginBtn.removeEventListener(MouseEvent.CLICK,onbeginClickHandle);
			ui.comBox.removeEventListener(NxComboBoxEvent.NXCOMBOBOX_CLICK,onBoxClickHandle);
			ui.windowBG.removeEventListener(NxWindowEvent.WINDOW_CLOSE,onClickCloseHandle);
		}
		private function onClickCloseHandle(e:NxWindowEvent):void
		{
			ui.hide();
		}
	}
}